package host.skiree.nettydemo.server.handler;

import host.skiree.nettydemo.message.RpcRequestMessage;
import host.skiree.nettydemo.message.RpcResponseMessage;
import host.skiree.nettydemo.service.HelloService;
import host.skiree.nettydemo.utils.ServicesFactory;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

/**
 * @author gcl
 * @date 2022/9/27 8:57
 */
public class DemoRpcHandler extends SimpleChannelInboundHandler<RpcRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcRequestMessage rpcRequestMessage) {
        RpcResponseMessage responseMessage = new RpcResponseMessage();
        responseMessage.setSequenceId(rpcRequestMessage.getSequenceId());
        try{
            HelloService service = (HelloService) ServicesFactory.getService(Class.forName(rpcRequestMessage.getInterfaceName()));
            Method method = service.getClass().getMethod(rpcRequestMessage.getMethodName(),rpcRequestMessage.getParameterTypes());
            Object invoke = method.invoke(service, rpcRequestMessage.getParameterValue());
            responseMessage.setReturnValue(invoke);
        }catch (Exception e){
            e.printStackTrace();
            // 包装一下异常时返回的数据，如果直接返回就太大了，影响到客户端的接受
            // 尽量使用e.getCause().getMessage()来获取信息，使用e.getMessage()捕获不到一些异常的信息
            responseMessage.setExceptionValue(new Exception("远程调用出错: "+e.getCause().getMessage()));

        }
        ctx.writeAndFlush(responseMessage);
    }

}
